<!-- RoomPanel.vue -->
<script setup>
import { ref, onMounted, computed } from 'vue';
import Modal from './Modal.vue';
import axios from 'axios';
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;  // 从环境变量获取基础 URL

const userInfo = ref(null);
let bill_type = ref(null);


onMounted(async () => {
  await loadUserInfo();
});

async function loadUserInfo() {
  try {
    const user = localStorage.getItem('user');
    if (user) {
      userInfo.value = JSON.parse(user);
      console.log(userInfo.value)
    } else {
      console.error('No user info found in localStorage.');
      // 这里可以添加跳转到登录界面的逻辑或显示错误消息
    }
  } catch (error) {
    console.error('Error loading user info:', error);
  }
}


const props = defineProps({
  all_rooms: Object,
  buttons: Array
});

const checkInFormState = ref({
  guest_id:"1203",
  guest_name:"肖可扬",
  days:1,
  deposit_amount:200
});

const selectedDetails = ref(null);
// 扁平化房间数组
const flatRooms = computed(() => {
  return props.all_rooms.floors.reduce((acc, floor) => [...acc, ...floor.rooms], []);
});

function handleSelect(room) {
  // 此处为模拟获取详细信息
  selectedDetails.value = room;
}

async function handleCheckIn(room, checkInFormState) {
  try {
    const response = await axios.post(`${apiBaseUrl}/waiter/check_in/create_accommodation_order`, {
      'waiter_id': 'waiter',
      'room_id': room.room_id,
      'guest_id': checkInFormState.guest_id,
      'guest_name': checkInFormState.guest_name,
      'days': checkInFormState.days,
      'date': getCurrentDate(),
      'deposit_amount': checkInFormState.deposit_amount
    });
    console.log('入住成功！响应:', response);
    alert('入住成功！');
  } catch (error) {
    console.error('提交失败:', error);
    alert('提交失败: ' + (error.response ? error.response.data.message : '无响应'));
  }
}


// 确保 userInfo 已加载再允许执行操作
const handleCheckOut = async (room) => {
  if (!userInfo.value) {
    alert('用户信息未加载！');

  }

  console.log(userInfo.value.id);
  console.log(room.room_id);
  try {
    const response = await axios.post(`${apiBaseUrl}/waiter/check_out/last_check_out`, {
      'waiter_id': userInfo.value.id,
      'room_id': room.room_id
    });
    alert('退房成功！');
    location.reload();

  } catch (error) {
    console.error('提交失败:', error);
    alert('提交失败');
  }
};


function confirmCheckIn(room) {
  console.log('确认入住:', room.room_id);
  // 实现确认入住逻辑
}
function windSpeedDescription(record) {
  const windSpeeds = {
    1: '低风',
    2: '中风',
    3: '高风'
  };
  return windSpeeds[record.wind_level] || '未知';
}

function modeDescription(record) {
  const modes = {
    'Cold': '制冷',
    'Hot': '制热',
    1: '制冷',
    0: '制热',
    'cold': '制冷',
    'hot': '制热',
  };
  return modes[record.mode] || '未知';
}

onMounted(async () => {
  const user = localStorage.getItem('user');
  if (user) {
    userInfo.value = JSON.parse(user);
  }

});

const checkInModal = ref(null);
const checkOutModal = ref(null);
const feeOfDayModal = ref(null);

const bill = ref(null);
const feeOfDay = ref(200);

function submitFeeOfDay(){
  feeOfDayModal.value.showModal();
}

function handleCheckInClick(room) {
  checkInModal.value.showModal();
}

async function handleCheckOutClick(room) {
  feeOfDayModal.value.closeModal();
  if (!userInfo.value) {
    alert('用户信息未加载！');
    return;
  }
  try {
    await axios.post(`${apiBaseUrl}/waiter/check_out`, {
      'waiter_id': userInfo.value.id,
      'room_id': room.room_id
    });

    checkOutModal.value.showModal();  // 显示模态窗口
  } catch (error) {
    console.error('获取详单信息失败:', error);
    alert('获取详单信息失败……');
  }
}

const detailedInfo = ref({});

const FeeDetailsModal = ref(false);

async function downloadDocument(docType, waiterId, roomId) {
  const url = `${apiBaseUrl}/waiter/check_out/get_fee_records`;

  alert(userInfo.value.id);
  // 将参数集成到 URL 查询字符串中
  const params = new URLSearchParams({
    type: docType,
    is_file: true,
    waiter_id: userInfo.value.id,
    room_id: roomId,
    fee_of_day: feeOfDay.value
  }).toString();

  const fullUrl = `${url}?${params}`; // 完整的 URL 包括查询参数

  try {
    // 发起 GET 请求，注意 responseType 为 'arraybuffer' 以处理文件下载
    const response = await axios.get(fullUrl, { responseType: 'arraybuffer' });

    console.log(response.data)
    // 创建Blob对象，设置文件类型
    const blob = new Blob([response.data], { type: "application/vnd.ms-excel" });
    console.log(blob)
    const objectUrl = URL.createObjectURL(blob); // 创建URL

    const link = document.createElement('a');
    link.href = objectUrl;
    link.download = `${docType}_${roomId}.xlsx`; // 自定义文件名，例如根据文档类型和房间号
    document.body.appendChild(link);
    link.click(); // 触发下载

    window.URL.revokeObjectURL(objectUrl); // 清理资源
    link.parentNode.removeChild(link); // 移除DOM中的链接元素
  } catch (error) {
    console.error('Download failed:', error);
    alert('文件下载失败！');
  }
}

function changeTwoDecimal(floatvar)
{
  var f_x = parseFloat(floatvar);
  if (isNaN(f_x))
  {
    alert('function:changeTwoDecimal->parameter error');
    return false;
  }
  var f_x = Math.round(floatvar*100)/100;
  return f_x;
}


async function displayBill(billType, waiterId, roomId) {
  try {
    bill_type.value = billType;
    const response = await axios.get(`${apiBaseUrl}/waiter/check_out/get_fee_records`, {
      params: {
        'type':bill_type.value,
        'is_file':false,
        'waiter_id':userInfo.value.id,
        'room_id':roomId,
        'fee_of_day':feeOfDay.value
      }
    });
    bill.value = response.data;  // 存储详单信息
    bill.value.total_fee = changeTwoDecimal(response.data.total_fee);
    if(bill_type.value === 'ac_bill'){
      bill.value.ac_fee = changeTwoDecimal(response.data.ac_fee);
    }
    console.log(response.data);
  } catch (error) {
    console.error('获取失败：', error);
    alert('获取失败！');
  }
}



async function showDetails() {
  const response = await axios.get(`${apiBaseUrl}/waiter/check_out/get_fee_records`, {
    params: {
      type: 'details',
      is_file: 'false',
      'waiter_id':userInfo.value.id,
      'room_id':selectedDetails.value.room_id,
      'fee_of_day':300
    }
  });
  detailedInfo.value = response.data;
  console.log(detailedInfo.value)
  FeeDetailsModal.value.showModal();
}


function getCurrentDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function calculateFutureDate(dateString, daysToAdd) {
  let date = new Date(dateString);
  date.setDate(date.getDate() + parseInt(daysToAdd)); // 在给定的日期上添加天数
  let dd = String(date.getDate()).padStart(2, '0');
  let mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，因此需要+1
  let yyyy = date.getFullYear();
  return `${yyyy}-${mm}-${dd}`;
}
</script>
<template>
  <div class="base">
    <div class="panel">

      <div v-if="all_rooms && all_rooms.floors" class="grid">
        <div
            v-for="room in flatRooms"
            :key="room.room_id"
            class="room"
            :class="{ '已预定': room.status === '已预定', '已入住': room.status === '已入住','空闲中': room.status === '空闲中' }"
            @click="handleSelect(room)"
        >
          <p>{{ room.room_id }}<br>{{ room.type }}<br>{{ room.status }}</p>
        </div>
      </div>
    </div>
    <div class="details">
      <div class="details-content">
        <div v-if="selectedDetails">
          <h2> {{ selectedDetails.room_id }} 房间详情</h2>
          <div class="item" style="margin: 5px">
            <div>{{ selectedDetails.type }} - {{ selectedDetails.status }}</div>
          </div>
          <div  class="item" style="margin: 5px">
            面积：20 ㎡
          </div>
          <button v-if="selectedDetails.status === '空闲中'" @click="handleCheckInClick(selectedDetails)" class="submit-button">办理入住</button>
          <button v-if="selectedDetails.status === '已入住'" @click="submitFeeOfDay()" class="submit-button">办理退房</button>
          <button v-if="selectedDetails.status === '已预定'" @click="confirmCheckIn(selectedDetails)" class="submit-button">确认入住</button>
        </div>
        <h2 v-else style="text-align: center">房间详情</h2>
        <h3 v-else style="text-align: center;color: gray;margin-top: 10px">请点击房间来查看详情</h3>
      </div>
    </div>
  </div>

  <!-- 其他内容 -->
  <Modal ref="checkInModal">
    <template v-slot:default>
      <!-- 入住表单内容 -->
      <div>
        <h1 style="text-align: center"> 登记入住{{ selectedDetails.room_id }}房间</h1>
        <form v-if="selectedDetails.status === '空闲中'" class="check-in-form">
          <div class="item">
            <label>顾客的ID：</label>
            <input type="text" name="guest_id" v-model="checkInFormState.guest_id">
          </div>

          <div class="item">
            <label>顾客姓名：</label>
            <input type="text" name="guest_name" v-model="checkInFormState.guest_name">
          </div>

          <div class="item">
            <label>入住天数：</label>
            <input type="text" name="days" v-model="checkInFormState.days">
          </div>

          <div class="item">
            <label>押金数额：</label>
            <input type="text" name="deposit_amount" v-model="checkInFormState.deposit_amount">
          </div>


          <button @click="handleCheckIn(selectedDetails,checkInFormState)" class="submit-button">入住</button>

        </form>
        <h2 style="text-align: center;margin-top: 10px">ID为{{ checkInFormState.guest_id }}的客人{{ checkInFormState.guest_name }}您好！</h2>
        <div style="text-align: center;margin-top: 10px">您的住宿时间将为{{ getCurrentDate() }} ~ {{ calculateFutureDate(getCurrentDate(),checkInFormState.days) }}</div>
        <div style="text-align: center">收取押金{{ checkInFormState.deposit_amount }}￥，将于退房时抵扣房费或退还</div>
      </div>
    </template>
  </Modal>

  <Modal ref="feeOfDayModal">
    <template v-slot:default>
        <div style="width: 100%;align-items: center">
        <h1 style="text-align: center">前台服务员输入房费</h1>
        <div class="item" style="align-items: center">
          <label>每日房间费用：</label>
          <input type="text" name="fee_of_day" v-model="feeOfDay">
        </div>
        <button @click="handleCheckOutClick(selectedDetails)" class="submit-button">提交并退房</button>
      </div>
    </template>
  </Modal>

  <Modal ref="checkOutModal">
    <template v-slot:default>
      <div style="width: 100%">
        <h1 style="margin-bottom: 5px"> 房间{{ selectedDetails.room_id }}退房业务 </h1>
        <div style="display: flex">
          <div v-if="bill_type === 'room_bill' && bill !== null" style="text-align: center;width: 100%">
            <h2>住宿账单</h2>
            <p>客人ID：{{ bill.guest_id }}</p>
            <p>房间号：{{ selectedDetails.room_id }}</p>
            <p>入住时间：{{ bill.checkin_time }}</p>
            <p>退房时间：{{ bill.checkout_time }}</p>
            <p>客房费用：{{ bill.room_fee }}￥</p>
            <p>押金：{{ bill.deposit }}￥</p>
          </div>
          <div v-else-if="bill_type === 'ac_bill'&& bill !== null" style="text-align: center;width: 100%">
            <h2>空调账单</h2>
            <p>客人ID：{{ bill.guest_id }}</p>
            <p>房间号：{{ selectedDetails.room_id }}</p>
            <p>空调费用：{{ bill.ac_fee }}￥</p>
          </div>
        </div>
        <h3 v-if="bill_type !== null" style="text-align: center;margin-top: 15px">总费用：{{ bill.total_fee }}￥</h3>

      </div>

      <div style="display: flex;height: 50px;width: 99%;position:absolute;bottom: 10px;left: 15px;">
        <button class="check-out-button" @click="displayBill('room_bill',userInfo.id,selectedDetails.room_id)">查看住宿账单</button>
        <button class="check-out-button" @click="displayBill('ac_bill',userInfo.id,selectedDetails.room_id)">查看空调账单</button>
        <button class="check-out-button" @click="showDetails()">查看空调详单</button>
        <button class="check-out-button" @click="downloadDocument(bill_type, userInfo.id,selectedDetails.room_id)" >打印</button>
        <button class="check-out-button" @click="handleCheckOut(selectedDetails)">确定退房</button>
      </div>
    </template>
  </Modal>

  <Modal ref="FeeDetailsModal">
    <template v-slot:default>
      <!-- 退房详单内容 -->
      <div>
        <h1 style="margin-bottom: 5px"> 房间{{ selectedDetails.room_id }} 空调使用详单 </h1>
        <div class="fee_details_list">
          <div v-for="record in detailedInfo">
            <h2> {{ record.detail_bill_id }} </h2>
            <p>客人ID：{{ record.guest_id }}</p>
            <p>房间号：{{ record.room_id }}</p>
            <p>此次费用：{{ record.fee }}￥</p>
            <p>此次费率：{{ record.fee_rate }}￥/度</p>
            <p>起始温度：{{ record.start_temp }}</p>
            <p>结束温度：{{ record.end_temp }}</p>
            <p>运行风速：{{ windSpeedDescription(record) }}</p>
            <p>空调模式：{{ modeDescription(record) }}</p>
            <p>开启时间：{{ record.start_time }}</p>
            <p>关闭时间：{{ record.end_time }}</p>
          </div>
        </div>
        <button @click="downloadDocument('details',userInfo.id,selectedDetails.room_id)" class="submit-button">打印详单</button>
      </div>
    </template>
  </Modal>
</template>

<style scoped>
.panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  position: fixed;
  top: 64px;
  left: 0;
  right: 400px;
  bottom: 10px;
}
.details {
  display: flex;
  padding: 10px 20px;
  justify-content: space-between;
  align-items: center;
  float: right;
  width: 410px;
  position: fixed;
  top: 64px;
  right: 10px;
  bottom: 10px;
}
.fee_details_list {
  display: flex;
  flex-direction: column; /* 堆叠内容 */
  padding: 10px;
  text-align: center;
  max-height: 300px; /* 设置最大高度 */
  width: 440px;
  overflow-y: auto; /* 允许垂直滚动 */
  margin-bottom: 20px; /* 底部间距 */
}

.bottom-container {
  display: flex;
  justify-content: flex-end; /* 按钮向右对齐 */
  margin-top: 10px; /* 顶部间距 */
}

.check-in-form{
  padding: 10px;
  display: flex;
  margin-top: 30px;
}
input[type="text"]{
  width: 100px;
  height: 25px;
  background-color: white;
  border-radius:10px;
  border:1px solid dodgerblue;
  color:black;
}

.details-content{
  width: 100%; /* 使表单宽度根据父容器调整 */
  padding: 30px;
  background-color: white;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  justify-content: center;
  text-align: center;
  align-items: center;
  border-radius: 8px;
  height: 100%;

}

.item{
  margin-bottom: 20px;
}

.grid {
  display: flex;
  flex-wrap: wrap; /* 允许内容换行显示 */
  align-items: flex-start; /* 使单元格在容器内顶部对齐 */
  width: 100%; /* 根据父容器调整宽度 */
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow-y: auto; /* 允许垂直滚动 */
  height: 100%; /* 减去padding的高度，保持内容完整可见 */
}

.room {
  width: 100px; /* 设置固定宽度 */
  height: 100px; /* 设置固定高度 */
  margin: 5px; /* 添加适量边距以避免过于拥挤 */
  display: flex;
  border-radius: 8px;
  justify-content: center; /* 内部内容水平居中 */
  align-items: center; /* 内部内容垂直居中 */
  text-align: center;
}

.room.已入住 {
  background-color: lightsalmon;
}

.room.空闲中 {
  background-color: lightgray;
}


.submit-button {
  padding: 20px 40px;
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-left: 10px; /* 按钮之间的间距 */
  position: absolute;
  right: 30px;
  bottom: 20px;
}

.submit-button:hover {
  background-color: #0056b3;
}

.check-out-button{
  background-color: #007BFF;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px; /* 按钮之间的间距 */
  height: 50px;
  width: 110px;
}
</style>
